package com.tanklab.signature.controller;

import com.tanklab.signature.common.util.JwtUtils;
import com.tanklab.signature.common.util.ResultCode;
import com.tanklab.signature.ds.resp.CommonResp;
import com.tanklab.signature.service.FileStorageService;
import com.tanklab.signature.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/signature/user")
public class UserAvatarController {

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtils jwtUtils;

    @ApiOperation("上传用户头像")
    @PostMapping("/avatar/upload")
    public CommonResp<Map<String, String>> uploadAvatar(
            @RequestParam("file") MultipartFile file,
            HttpServletRequest request) {

        CommonResp<Map<String, String>> resp = new CommonResp<>();

        String token = request.getHeader("Authorization");
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }

        // 从Token提取openid (无需再验证token)
        String openid = jwtUtils.getOpenidFromToken(token);

        // 验证文件是否为空
        if (file.isEmpty()) {
            resp.setRet(ResultCode.PARAM_ERROR);
            resp.setMsg("文件不能为空");
            return resp;
        }

        // 验证文件类型
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            resp.setRet(ResultCode.PARAM_ERROR);
            resp.setMsg("只允许上传图片文件");
            return resp;
        }

        try {
            // 存储头像并获取URL
            String avatarUrl = fileStorageService.storeAvatar(file);

            // 更新用户头像信息
            boolean updated = userService.updateUserAvatar(openid, avatarUrl);

            if (!updated) {
                resp.setRet(ResultCode.USER_NOT_EXIST);
                resp.setMsg("用户不存在");
                return resp;
            }

            // 返回结果
            Map<String, String> data = new HashMap<>();
            data.put("avatarUrl", avatarUrl);

            resp.setRet(ResultCode.SUCCESS);
            resp.setMsg("头像上传成功");
            resp.setData(data);

            return resp;

        } catch (IOException e) {
            resp.setRet(ResultCode.ERROR);
            resp.setMsg("头像上传失败: " + e.getMessage());
            return resp;
        }
    }
}